/* eslint-disable import/order */
import '@/utils/highlight';
import ReactQuill, { ReactQuillProps } from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import Toolbar, { formats } from './toolbar';
import { useSettings } from '@/store/settingStore';
import { useThemeToken } from '@/theme/hooks';
import { StyledEditor } from './styles';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import apiClient from '@/api/apiClient';

interface Props extends ReactQuillProps {
  sample?: boolean;
  disabled?: boolean;
  showToolbar?: boolean;
}
export default function Editor({
  id = 'slash-quill',
  sample = false,
  disabled = false,
  showToolbar = true,
  ...other
}: Props) {
  const token = useThemeToken();
  const [enable, setEnable] = useState<boolean>(false);
  const { themeMode } = useSettings();
  const quillRef = useRef<any>(null); // 用于获取 Quill 实例
  useEffect(() => {
    setEnable(true);
  }, []);
  const uploadImage = useCallback((file) => {
    const formData = new FormData();
    formData.append('file', file);
    return apiClient
      .post({
        url: '/file/oss/upload',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data', // 上传文件需要设置此头信息
        },
      })
      .then((res) => {
        return res;
      });
  }, []);

  const modules = useMemo(
    () => ({
      toolbar: {
        container: `#${id}`,
        handlers: {
          // 图片上传处理函数
          image: async () => {
            const input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.click();

            input.onchange = async () => {
              const file = input.files?.[0];
              if (file) {
                try {
                  const url = await uploadImage(file); // 上传图片
                  if (url && quillRef.current) {
                    const quill = quillRef.current.getEditor(); // 获取 Quill 实例
                    const range = quill.getSelection(true); // 获取当前光标位置
                    quill.insertEmbed(range.index, 'image', url); // 插入图片
                    quill.setSelection(range.index + 1); // 移动光标到图片后面
                  }
                } catch (error) {
                  console.error('Failed to upload image:', error);
                }
              }
            };
          },
        },
      },
      history: {
        delay: 500,
        maxStack: 100,
        userOnly: true,
      },
      syntax: true, // 启用语法高亮
      clipboard: {
        matchVisual: false,
      },
    }),
    [id, uploadImage],
  );

  return (
    <StyledEditor $token={token} $thememode={themeMode}>
      <Toolbar id={id} isSimple={sample} />
      {enable && (
        <ReactQuill
          readOnly={disabled}
          ref={quillRef} // 绑定 ref
          modules={modules}
          formats={formats}
          {...other}
          placeholder="请输入文本和图片"
        />
      )}
    </StyledEditor>
  );
}
